package net.tngou.iask.action.my;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.FileBasedConfigurationBuilder;
import org.apache.commons.configuration2.builder.fluent.Parameters;
import org.apache.commons.configuration2.ex.ConfigurationException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.tngou.iask.action.BaseAction;
import net.tngou.iask.enums.CookieEnum;
import net.tngou.iask.http.HttpRequest;
import net.tngou.iask.http.HttpResponse;
import net.tngou.iask.http.RequestContext;
import net.tngou.iask.http.ResponseContext;
import net.tngou.iask.http.SessionContext;
import net.tngou.iask.jdbc.DBManager;
import net.tngou.iask.pojo.User;
import net.tngou.iask.util.StringUtil;








/**
 * Servlet的接口 默认的URL :servlet/*<br>
 * 同时也可以配置文件 如：<br >
 * 
 *  <br >
 * <servlet><br >
 *   <servlet-name>servlet</servlet-name><br >
 *   <servlet-class>com.spem.action.ServletManage</servlet-class><br >
 *   <init-param><br >
 *   <param-name>module</param-name><br >
 *   <param-value>module.properties</param-value><br >
 *   </init-param><br >
 *   <!-- 是否使用 异步处理  默认是false 不使用-->
 *   <async-supported>true</async-supported><br >
 *   <multipart-config></multipart-config><br >
 * </servlet><br >
 * <br >
 * <br >
  * <servlet-mapping><br >
 *   <servlet-name>servlet</servlet-name><br >
 *   <url-pattern>/my/*</url-pattern><br >
 * </servlet-mapping><br >
 * <br >
 * @author PICOHOOD1
 *
 */
@WebServlet(urlPatterns= {"/my/*","/my"})
public class ServletMy extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private final static Logger log= LoggerFactory.getLogger(ServletMy.class);
	private static String packages ;//action的路径包
	
	
	/**
	 * 初始化,主要是完成module的内存加载<br>
	 * 从配置文件中读取module对于类
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {
		
		packages= this.getClass().getPackage().getName(); 
		super.init();
	}
	
	
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
		  throws ServletException, IOException{
	  

	  HttpRequest request=new RequestContext(req);
	  HttpResponse response = new ResponseContext(resp);
	  User user = new SessionContext().getUser(_GetCookieID(request, response));
	  if(user==null){//用户认证
		  response.sendRedirect(getDomain());
		  return;
	  }
	 String module= request.getModule();//取得调用类
	 String action= request.getAction();  //取得调方法
	 BaseAction baseAction = _retrieveModule(module); //初始调用类
	 if (baseAction==null) 
	 {
		 //没有找到Module 返回404
		response.sendError(HttpServletResponse.SC_NOT_FOUND);//返回404
		return ;
	 }
	 	
	baseAction.init(request, response); //初始化baseAction
	if (StringUtils.isNotEmpty(action))
	{
		baseAction.run(action); //执行
	}
	else //默认执行
	{
		try {
			baseAction.execute();
		} catch (IOException e) {
			
			e.printStackTrace();
		}finally
		{
			DBManager.closeConnection(); //释放数据库连接到连接池中
		}
		
	}
	
	
	
  }
  
  
  /**
   * 销毁
   */
  @Override
  public void destroy() {
	  	log.debug("destroy");
		super.destroy();
	}

  
  
  /**
   * 通过类的名称 ，返回名称对于的对象。如果没有找到该对象，返回NULL
   * @param moduleClass 类的名称 如：test.action.TestAction
   * @return 返回 Object对象
   */
  private  BaseAction _retrieveModule(String module) 
  {
	 
	  if(module==null)module="index";
	  module=StringUtils.capitalize(module+"Action");//module后添加Action 并且把第一个字母转为大写
	  String moduleClass=packages+"."+module;
		try {
				BaseAction baseAction;
				baseAction = (BaseAction) Class.forName(moduleClass).newInstance();
				return baseAction;
			} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
			
				log.error("没有对用的{}类",moduleClass);
				
				e.printStackTrace();
			}
			
		
		return null;
	
  }
  
  
	
	 public String _GetCookieID( HttpRequest request,HttpResponse response) {
		 Cookie[] cookies = request.getCookies();//这样便可以获取一个cookie数组
		 
		 if(cookies==null)
			 return null;
		 
		 for(Cookie cookie : cookies){
			 if(cookie.getName().equals(CookieEnum.access_token.toString()))
			 {
				String tngou_id=cookie.getValue();
				 if(StringUtil.isNoneBlank(tngou_id)&&new SessionContext().getUser(tngou_id)==null)
				{
						response.removeAutoLoginCookie(); //移除登录Cook；
						return null;
				}
				 return tngou_id;
			 }
		   
		 }
		return null;
	}

	 protected String getDomain()
	 {
		 return ststeminfo().get("domain");
//		 return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +  request.getContextPath()+ "/";	 
	 }
	
	 
	 protected Map<String ,String> ststeminfo() {
		
		 Parameters params = new Parameters();
			FileBasedConfigurationBuilder<PropertiesConfiguration> builder =
			    new FileBasedConfigurationBuilder<PropertiesConfiguration>(PropertiesConfiguration.class)
			    .configure(params.properties()
			        .setFileName("info.properties"));	//那么这个文件会自动在下面几个地方被搜寻：当前目录 、用户主目录 、classpath
			try {
				PropertiesConfiguration properties = builder.getConfiguration();
				Map<String, String> cp_props =new HashMap<String, String>();//使用cp_props做临时的配置文件的存储
				Iterator<String> iterable = properties.getKeys();//取得配置文件中的key
				while (iterable.hasNext()) {
					String skey=iterable.next();
					  cp_props.put(skey, properties.getString(skey));				
				}
				return cp_props;
			} catch (ConfigurationException e) {
				e.printStackTrace();
			}
			return new HashMap<>();
	}

}
